package com.wngbms.netty._02http.client;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.LockSupport;

@Slf4j
public class HttpKeepAliveTest {

    // ns us ms s
    public static void parkMs(long l) {
        LockSupport.parkNanos(l * 1000L * 1000L);
    }

    public static void main(String[] args) throws IOException {
        String url = "http://192.168.31.80:7890/";

        Properties properties = System.getProperties();
        // 默认为true, 改成false 则不会使用长链接, 会创建多个tcp链接
//        System.setProperty("http.keepAlive", String.valueOf(false));
        System.setProperty("http.maxConnections", String.valueOf(1));
        log.info("property:{}", properties);

        ExecutorService executorService = Executors.newFixedThreadPool(10);

        for (int i = 0; i < 10; i++) {
            int fi = i;
            executorService.submit(() -> {
                try {
                    jdkGet(url + fi);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
            parkMs(500L);
        }
    }

    public static void jdkGet(String url) throws IOException {
        InputStream inputStream = null;
        HttpURLConnection httpURLConnection = null;

        StringBuilder builder = new StringBuilder();
        URL serviceUrl = new URL(url);

        httpURLConnection = (HttpURLConnection) serviceUrl.openConnection();
        httpURLConnection.setRequestMethod("GET");
        httpURLConnection.setRequestProperty("Accept", "application/json");
        // 不会启用长链接, 会创建多个tcp链接
//        httpURLConnection.setRequestProperty("Connection", "close");
        // 可以注释掉, 默认是启用长链接的.
//        httpURLConnection.setRequestProperty("Connection", "keep-alive");
        httpURLConnection.connect();

        if (httpURLConnection.getResponseCode() != 200) {
            log.error("failed");
            return;
        }

        Map<String, List<String>> headerFields = httpURLConnection.getHeaderFields();
        log.info("resp headers:{}", headerFields);
        Object content = httpURLConnection.getContent();
        log.info("resp content:{}", content);
        inputStream = httpURLConnection.getInputStream();
        byte[] buf = new byte[1024];
        int length = 0;
        while ((length = inputStream.read(buf)) != -1) {
            builder.append(new String(buf, 0, length));
        }

        if (inputStream != null) {
            /**
             * 2、想要启用keepAlive，程序请求完毕后，必须调用HttpURLConnection.getInputStream().close()
             * （表示归还长连接给缓存，以供下次同host:port的请求重用底层socket连接），
             * 而不能调用HttpURLConnection.disconnect()（表示关闭底层socket连接，不会启用keepAlive）
             *
             * 如果注释掉关闭输入流, 则会创建多个tcp链接
             */
            inputStream.close();
        }

        // 不注释掉也会使用长链接
        httpURLConnection.disconnect();
        log.info("resp:{}", builder.toString());
    }

}
